# this script calculates the current dividend yield 

from <- "2000-01-01"
to <- "2013-06-30"

divPayers <- getSymbolNames.wikifolio.DividendPayer(excludeTrickySplits=TRUE)
divPayers
# divPayers <- getSymbolNames.wikifolio()

for (i in 1:nrow(divPayers)) {
  TS <- getSymbols(divPayers[i,"symbol"], src="wikifolio", auto.assign=FALSE, adjust=NULL, datefrom=from, dateto=to)  
  div <- getDividends.wikifolio(divPayers[i,"symbol"], datefrom=from, dateto=to)
  splits <- getSplits.wikifolio(divPayers[i,"symbol"], datefrom=from, dateto=to)
  
  if(!is.na(div) && is.xts(div) && nrow(div) > 0) {
    
    # adjust for splits: code copied and adapted from quantmod::adjustOHLC
    #if (is.xts(splits) && is.xts(div) && nrow(splits) > 0 && nrow(div) > 0) {
    #  div <- div * 1/adjRatios(splits = merge(splits, index(div)))[, 1]
    #  colnames(div) <- "Dividend"
    #}
    ratios <- adjRatios(splits, div, Cl(TS))
    Adjusted <- Cl(TS) * ratios[,1]
    TS <- structure(cbind((ratios[,1] * (Op(TS) - Cl(TS)) + Adjusted), 
                          (ratios[,1] * (Hi(TS) - Cl(TS)) + Adjusted), 
                          (ratios[,1] * (Lo(TS) - Cl(TS)) + Adjusted), 
                          Adjusted, 
                          if (has.Vo(TS)) Vo(TS)
                          else NULL, 
                          if (has.Ad(TS)) Ad(TS)
                          else NULL), 
                    .Dimnames = list(NULL, colnames(TS)))
    
    if (nrow(TS) > 250) {
      # assume the daily dividend "payment" to be constant within a quarter
      TSComb <- merge(Cl(TS), div, fill=0)
      DailyDiv <- structure(apply.quarterly(TSComb[,2], mean), 
                            .Dimnames = list(NULL, "DailyDividend"))
      TSComb <- na.locf(merge(TSComb, DailyDiv), fromLast=TRUE)
      # if no dividend payment within from-to date
      if (is.na(TSComb[1,3])) {
        TSComb[,3]=0
      }
      
      # clean for events like 2001-09-12, where there might be dividend poyments but
      # was no trading, resulting in Inf Yield on that day
      TSComb[(TSComb[,1]==0)] <- NA
      TSComb[,1] <- na.locf(TSComb[,1])
      
      # calculate yearly dividend and yield
      TSComb <- merge(TSComb, structure(runSum(TSComb[,"DailyDividend"], n=250), 
                                        .Dimnames = list(NULL, "YearlyDividend")))
      TSComb <- merge(TSComb, structure(TSComb[,"YearlyDividend"]/TSComb[,1]*100, 
                                        .Dimnames = list(NULL, "Yield")))
      
      # plot yield and dividend payments
      print(paste("now plotting", divPayers[i,"symbol"]))
      plot(as.zoo(cbind(TSComb[,"Yield"], div)),
           main=paste(divPayers[i,"symbol"], "Dividend Yield"),
           heights=c(2,1),
           ylim=list(c(0,max(TSComb[,"Yield"], na.rm=TRUE)), 
                     c(0,max(div))),
           xlab=NULL, ylab=c("Yield [%]", "Dividend [$]"),
           col="blue",
           las=1, type=c("l", "p"), yax.flip=1)
      par(bg="white")
      # write into plot
      dev.copy(png,paste(divPayers[i,"symbol"], "_yield.png", sep=""))
      dev.off()
    } else {
      print (paste("ERROR: Not enough data for symbol", divPayers[i,"symbol"]))
    } 
  } else {
    print (paste("ERROR: No dividends for symbol", divPayers[i,"symbol"]))
  }
}
